package edu.sandau.f210153.f21010536.controller;


import edu.sandau.f210153.f21010536.model.School;
import edu.sandau.f210153.f21010536.model.School;
import edu.sandau.f210153.f21010536.repository.SchoolRepository;
import edu.sandau.f210153.f21010536.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

@Controller
public class SchoolController {
    @Autowired
    private SchoolRepository schoolRepository;
    @Autowired
    private SchoolService schoolService;
    @RequestMapping( "school")
    public String getSchool(ModelMap map, School school) {
        if (StringUtils.isEmpty(school.getName())){
            school.setName(null);
        }
        if (StringUtils.isEmpty(school.getDizhi())) {
            school.setDizhi(null);
        }
        map.put("schools", schoolRepository.findByNameOrDizhi(school.getName(),school.getDizhi()));
        if (StringUtils.isEmpty(school.getName())&&StringUtils.isEmpty(school.getDizhi())){
            map.put("school",schoolRepository.findAll());
        }
        return "list";
    }

    @RequestMapping("school/delete/{id}")
    public String delete(@PathVariable Long id){
        schoolService.delete(id);
        return "redirect:/school";
    }

    @RequestMapping("school/create")
    public String create(){return "create";}

    @RequestMapping("school/save")
    public String save(@RequestParam String name,@RequestParam String sex,@RequestParam String xueyuan,@RequestParam int num,@RequestParam String time,@RequestParam String dizhi){
        School d = new School();
        d.setName(name);
        d.setSex(sex);
        d.setXueyuan(xueyuan);
        d.setNum(num);
        d.setTime(time);
        d.setDizhi(dizhi);
        schoolService.save(d);
        return "redirect:/school";
    }

    @RequestMapping("school/update/{id}")
    public String update(ModelMap map,@PathVariable Long id){
        map.put("school",schoolService.get(id));
        delete(id);
        return "update";
    }

    @RequestMapping("school/edit")
    public String edit(School school){
        schoolService.save(school);
        return "redirect:/school";
    }
}
